﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;
using HTML5Converter.Entities;


namespace HTML5Converter
{
    /// <summary>
    /// Interaction logic for UC_AddEditRules.xaml
    /// </summary>
    public partial class UC_ReplaceRemove : UserControl
    {
        public UC_ReplaceRemove()
        {
            InitializeComponent();

            BindGrid();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtStartsWith.Text))
            {
                MessageBox.Show("Starts with text cannot be empty.");
                txtStartsWith.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtContains.Text))
            {
                MessageBox.Show("Contains text cannot be empty,");
                txtContains.Focus();
                return;
            }
            if (cmbWhere.SelectedIndex <= 0)
            {
                MessageBox.Show("Text loaction data not selected.");
                cmbWhere.Focus();
                return;
            }
            if (cmbAction.SelectedIndex <= 0)
            {
                MessageBox.Show("Action should be taken not selected.");
                cmbAction.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txtReplaceWith.Text))
            {
                if (chkReplaceRelativeTags.IsEnabled && (bool)chkReplaceRelativeTags.IsChecked)
                {
                    MessageBox.Show("Replace text cannot be empty.");
                    txtReplaceWith.Focus();
                    return;
                }
                else if (cmbAction.SelectedIndex == 2)
                {
                    MessageBox.Show("Replace text cannot be empty.");
                    txtReplaceWith.Focus();
                    return;
                }
            }
            lstReplace.Add(new ReplaceRemove()
            {
                StartsWith = txtStartsWith.Text,
                Contains = txtContains.Text,
                Where = (WhereEnum)(cmbWhere.SelectedItem as ComboBoxItem).Name[0],
                Action = (ActionEnum)(cmbAction.SelectedItem as ComboBoxItem).Name[0],
                ReplaceRelativeTags = (bool)chkReplaceRelativeTags.IsChecked,
                ReplaceWith = txtReplaceWith.Text
            });

            //MessageBox.Show("Save Succesful");

            if (!new FileInfo(App.Html5RulesFilePath).Exists)
            {
                XmlTextWriter tw = new XmlTextWriter(App.Html5RulesFilePath, null);
                tw.WriteStartDocument();
                tw.WriteComment("This is Rules for HTML5 convertion");
                tw.WriteStartElement("Rules");

                tw.WriteStartElement("ReplaceRemove");

                tw.WriteStartElement("StartsWith");
                tw.WriteString(txtStartsWith.Text);
                tw.WriteEndElement();

                tw.WriteStartElement("Contains");
                tw.WriteString(txtContains.Text);
                tw.WriteEndElement();

                tw.WriteStartElement("Where");
                tw.WriteString((cmbWhere.SelectedItem as ComboBoxItem).Name);
                tw.WriteEndElement();

                tw.WriteStartElement("Action");
                tw.WriteString((cmbAction.SelectedItem as ComboBoxItem).Name);
                tw.WriteEndElement();

                tw.WriteStartElement("ReplaceRelativeTags");
                tw.WriteString(((bool)chkReplaceRelativeTags.IsChecked).ToString());
                tw.WriteEndElement();

                tw.WriteStartElement("ReplaceWith");
                tw.WriteString(txtReplaceWith.Text);
                tw.WriteEndElement();

                tw.WriteEndElement();
                tw.WriteEndElement();
                tw.WriteEndDocument();
                tw.Flush();
                tw.Close();
            }
            else
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(App.Html5RulesFilePath);
                XmlNode xmlRoot = doc.DocumentElement;
                XmlNode newNod = doc.CreateElement("ReplaceRemove");
                xmlRoot.AppendChild(newNod);
                xmlRoot = newNod;

                newNod = doc.CreateElement("StartsWith");
                XmlText nodText = doc.CreateTextNode(txtStartsWith.Text);
                newNod.AppendChild(nodText);
                xmlRoot.AppendChild(newNod);


                newNod = doc.CreateElement("Contains");
                nodText = doc.CreateTextNode(txtContains.Text);
                newNod.AppendChild(nodText);
                xmlRoot.AppendChild(newNod);

                newNod = doc.CreateElement("Where");
                nodText = doc.CreateTextNode((cmbWhere.SelectedItem as ComboBoxItem).Name);
                newNod.AppendChild(nodText);
                xmlRoot.AppendChild(newNod);

                newNod = doc.CreateElement("Action");
                nodText = doc.CreateTextNode((cmbAction.SelectedItem as ComboBoxItem).Name);
                newNod.AppendChild(nodText);
                xmlRoot.AppendChild(newNod);

                newNod = doc.CreateElement("ReplaceRelativeTags");
                nodText = doc.CreateTextNode(((bool)chkReplaceRelativeTags.IsChecked).ToString());
                newNod.AppendChild(nodText);
                xmlRoot.AppendChild(newNod);

                newNod = doc.CreateElement("ReplaceWith");
                nodText = doc.CreateTextNode(txtReplaceWith.Text);
                newNod.AppendChild(nodText);

                xmlRoot.AppendChild(newNod);

                doc.Save(App.Html5RulesFilePath);
            }

            BindGrid();

            ResetFeilds();
            (Application.Current.MainWindow as MainWindow).LoadXmlData();
        }

        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            ResetFeilds();
        }

        private void cmbWhere_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbWhere.SelectedIndex == 1 && cmbAction.SelectedIndex == 1)
            {
                chkReplaceRelativeTags.IsEnabled = true;
            }
            else
                chkReplaceRelativeTags.IsEnabled = false;

            if (cmbWhere.SelectedIndex != 1)
            {
                chkReplaceRelativeTags.IsChecked = false;
            }
        }

        private void cmbAction_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbWhere.SelectedIndex == 1 && cmbAction.SelectedIndex == 1)
            {
                chkReplaceRelativeTags.IsEnabled = true;
            }
            else
                chkReplaceRelativeTags.IsEnabled = false;

            if (cmbAction.SelectedIndex == 1)
            {
                txtReplaceWith.IsEnabled = false;
            }
            else
            {
                chkReplaceRelativeTags.IsChecked = false;
                txtReplaceWith.IsEnabled = true;
            }
        }

        string strReplaceWithPreservedText = string.Empty;

        private void chkReplaceRelativeTags_Checked(object sender, RoutedEventArgs e)
        {
            txtReplaceWith.Text = strReplaceWithPreservedText;
            txtReplaceWith.IsEnabled = true;
        }

        private void chkReplaceRelativeTags_Unchecked(object sender, RoutedEventArgs e)
        {
            strReplaceWithPreservedText = txtReplaceWith.Text;
            txtReplaceWith.Text = string.Empty;
            txtReplaceWith.IsEnabled = false;
        }

        private void ResetFeilds()
        {
            txtStartsWith.Text = string.Empty;
            txtContains.Text = string.Empty;
            txtReplaceWith.Text = string.Empty;
            cmbWhere.SelectedIndex = 0;
            cmbAction.SelectedIndex = 0;
            chkReplaceRelativeTags.IsChecked = false;
            chkReplaceRelativeTags.IsEnabled = false;
            btnSave.IsEnabled = true;
        }

        private void BindGrid()
        {
            grdReplaceRemove.ItemsSource = string.Empty;
            grdReplaceRemove.ItemsSource = lstReplace;
        }


        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            ReplaceRemove objReplaceRemove = ((FrameworkElement)sender).DataContext as ReplaceRemove;
            lstReplace.Remove(objReplaceRemove);
            XDocument xdoc = XDocument.Load(App.Html5RulesFilePath);

            //var a = from row in xdoc.Root.Descendants("ReplaceRemove")
            //        where row.Element("StartsWith").Value == objReplaceRemove.StartsWith
            //        && row.Element("Contains").Value == objReplaceRemove.Contains
            //        select row;

            xdoc.Root.Descendants("ReplaceRemove").Where(no => no.Element("StartsWith").Value == objReplaceRemove.StartsWith && no.Element("Contains").Value == objReplaceRemove.Contains && (WhereEnum)no.Element("Where").Value[0] == objReplaceRemove.Where
                  && (ActionEnum)no.Element("Action").Value[0] == objReplaceRemove.Action && bool.Parse(no.Element("ReplaceRelativeTags").Value) == objReplaceRemove.ReplaceRelativeTags && no.Element("ReplaceWith").Value == objReplaceRemove.ReplaceWith).Remove();
            xdoc.Save(App.Html5RulesFilePath);
            BindGrid();
        }

        public List<ReplaceRemove> lstReplace
        {
            get
            {
                return (Application.Current.MainWindow as MainWindow).ListReplaceRemove;
            }
        }

        private void grdReplaceRemove_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ReplaceRemove objReplace = e.AddedItems[0] as ReplaceRemove;
            txtStartsWith.Text = objReplace.StartsWith;
            txtContains.Text = objReplace.Contains;
            for (int i = 0; i < cmbWhere.Items.Count; i++)
            {
                if (!string.IsNullOrEmpty((cmbWhere.Items[i] as ComboBoxItem).Name) && (cmbWhere.Items[i] as ComboBoxItem).Name[0] == (char)objReplace.Where)
                {
                    (cmbWhere.Items[i] as ComboBoxItem).IsSelected = true;
                    break;
                }
            }
            for (int i = 0; i < cmbAction.Items.Count; i++)
            {
                if (!string.IsNullOrEmpty((cmbAction.Items[i] as ComboBoxItem).Name) && (cmbAction.Items[i] as ComboBoxItem).Name[0] == (char)objReplace.Action)
                {
                    (cmbAction.Items[i] as ComboBoxItem).IsSelected = true;
                    break;
                }
            }
            chkReplaceRelativeTags.IsChecked = objReplace.ReplaceRelativeTags;
            txtReplaceWith.Text = objReplace.ReplaceWith;
            btnSave.IsEnabled = false;
        }
    }
}
